﻿using AutoMapper;
using MediatR;
using Traceability.App.Api.Application.Command.Add;
using Traceability.App.Domain;
using Traceability.App.ErrorCode;
using Traceability.App.Instructure;

namespace Traceability.App.Api.Application.Handler.Add
{
    public class AddDeepHandler : IRequestHandler<AddDeepCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<DeepProcessing> deepRepo;
        private readonly IMapper mapper;

        public AddDeepHandler(IBaseRepository<DeepProcessing> deepRepo,IMapper mapper) 
        {
            this.deepRepo = deepRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(AddDeepCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var deep = deepRepo.GetAll().Where(x => x.Batch == request.Batch).FirstOrDefault();
            if (deep==null)
            {
                var entity = mapper.Map<DeepProcessing>(request);
                deepRepo.Add(entity);   
            }
            else
            {
                deep.HeaderName=request.HeaderName;
                deep.Team=request.Team;
                deepRepo.Update(deep);
            }
            res.Code = ApiEnum.Success;
            res.Msg = "设置深加工信息成功";
            return Task.FromResult(res);
        }
    }
}
